package middlewares

import (
	"fmt"
	"gozero-microservices/gateway-api/utils"
	"net/http"
	"time"

	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/zeromicro/go-zero/rest/httpx"
)

/**
 * 熔断
 *
 * @param http.HandlerFunc next ------------------------------必传
 * @return http.HandlerFunc
 * @author huwl
 */
func CircuitbreakerMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		e, b := sentinel.Entry(utils.CircuitbreakerResource, sentinel.WithResourceType(base.ResTypeWeb), sentinel.WithTrafficType(base.Inbound))
		if b != nil {
			httpx.OkJsonCtx(r.Context(), w, utils.SuccessOutput("静态数据"))
			return
		} else {
			defer e.Exit() // 不要忘了加它
			if time.Now().Unix()%2 == 0 {
				sentinel.TraceError(e, fmt.Errorf("sentinel TraceError"))
				httpx.OkJsonCtx(r.Context(), w, utils.ErrorOutput("异常"))
				return
			}
		}

		next(w, r)
	}
}
